﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace cz.zcu.PreSti.Components
{
    public class DiscreteGenerator : BaseComponent
    {
        private Random r;

        private List<DiscreteGeneratorPossibility> values = new List<DiscreteGeneratorPossibility>();

        #region properties

        public virtual List<DiscreteGeneratorPossibility> Values
        {
            get
            {
                return values;
            }
            set
            {
                values = value;
            }
        }

        public class DiscreteGeneratorPossibility
        {
            private float probability = 0;
            private string val = "";

            public DiscreteGeneratorPossibility(float probability, string value)
            {
                this.Probability = probability;
                this.Value = value;
            }
            
            public float Probability
            {
                get
                {
                    return probability;
                }
                set
                {
                    probability = value;
                }
            }

            public string Value
            {
                get
                {
                    return val;
                }
                set
                {
                    val = value;
                }
            }
        }

        #endregion
        public DiscreteGenerator()
            : base(0, 1)
        {
            r = new Random(this.GetHashCode()); //bug 6911: constructor without parameter makes all generators not really random
        }

        public override object getValueFromGetter(int getterN)
        {
            switch (getterN)
            {
                case 0:
                    double random;
                    float sum = 0;
                    string value = "";
                    random = r.NextDouble();
                    foreach (DiscreteGeneratorPossibility p in Values)
                    {
                        sum += p.Probability / 100;
                        if (sum > random)
                        {
                            value = p.Value;
                            break;
                        }
                    }
                    return value;
            }
            return base.getValueFromGetter(getterN);
        }

    }
}
